package.path=package.path..";../itemdb/?.lua"
require("curl")
require("xml")
require("lsqlite3")

local VERBOSE = VERBOSE or nil
local BATTLEGROUP = BATTLEGROUP or "Cataclysme"
local MAX_PAGE = MAX_PAGE or 5

local real_download
do
	local temp
	local write = function (s, len)
		temp[#temp + 1] = s
		return len
	end
	local function download(url)
		if VERBOSE then print("GET", url) io.flush() end
		temp = {}
		local c = curl.easy_init()
		c:setopt(curl.OPT_URL, url)
		c:setopt(curl.OPT_USERAGENT, "Firefox/2.0")
		if COOKIE then
			c:setopt(curl.OPT_HTTPHEADER, COOKIE)
		end
		c:setopt(curl.OPT_WRITEFUNCTION, write)
		local err, info = c:perform()
		if err ~= 0 then
			return
		else
			temp = table.concat(temp)
			if temp:len() > 0 then
				return temp
			end
		end
	end
	local function pause(time)
		local endtime = os.clock() + time
		repeat
		until os.clock() > endtime
	end
	function real_download(url)
		local trycount = 0
		while trycount < 10 do
			trycount = trycount + 1
			local data = download(url)
			if not data:find("<errorhtml/>") then
				return data
			end
			pause(1)
		end
		print("DOWNLOAD FAILED", url)
	end
end

db = sqlite3.open("armory.db")
db:exec([[
CREATE TABLE IF NOT EXISTS cache (
	url TEXT,
	content BLOB,
	time TEXT,
	PRIMARY KEY (url)
)]])
local CACHE_TIMEOUT = CACHE_TIMEOUT or "+7 day"
local select_stmt = db:prepare("SELECT content FROM cache WHERE url = ? AND datetime(time, '"..CACHE_TIMEOUT.."') > datetime('now')")
local insert_stmt = db:prepare("INSERT OR REPLACE INTO cache VALUES (?, ?, CURRENT_TIMESTAMP)")
local download = function (url)
	select_stmt:bind_values(url)
	local result = select_stmt:step()
	if result == sqlite3.ROW then
		result = select_stmt:get_value(0)
		select_stmt:reset()
		return result
	else
		select_stmt:reset()
	end
	local content = real_download(url)
	if content then
		insert_stmt:bind_values(url, content)
		insert_stmt:step()
		insert_stmt:reset()
	end
	return content
end

local function get_character_info(realm, name)
	download(("http://eu.wowarmory.com/character-sheet.xml?r=%s&n=%s"):format(curl.escape(realm), curl.escape(name)))
	download(("http://eu.wowarmory.com/character-talents.xml?r=%s&n=%s"):format(curl.escape(realm), curl.escape(name)))
end

local guildcache = {}
local function get_guild_roster(realm, name)
	local key = realm.."%"..name
	if not guildcache[key] then
		guildcache[key] = true
		local data = download(("http://eu.wowarmory.com/guild-info.xml?r=%s&n=%s"):format(curl.escape(realm), curl.escape(name)))
		data = xml.parse(data)
		data = data:get_first_child("guildInfo")
		data = data:get_first_child("guild")
		if not data then
			print("Unknown guild", realm, name)
		else
			data = data:get_first_child("members")
			for member in data:iterate_children("character") do
				get_character_info(realm, member:get_attribute("name"))
			end
		end
	end
end

local function get_arena_team(team)
	local realm = team:get_attribute("realm")
	local name = team:get_attribute("name")
	local data = download(("http://eu.wowarmory.com/team-info.xml?r=%s&t=%s&ts=2"):format(curl.escape(realm), curl.escape(name)))
	data = xml.parse(data):get_first_child("teamInfo"):get_first_child("arenaTeam"):get_first_child("members")
	for member in data:iterate_children("character") do
		local guild = member:get_attribute("guild")
		if guild then
			get_guild_roster(realm, guild)
		else
			get_character_info(realm, member:get_attribute("name"))
		end
	end
end

local function get_battlegroup_info(battlegroup, max_page)
	for page = 1, max_page do
		local data = download(("http://eu.wowarmory.com/arena-ladder.xml?b=%s&p=%d"):format(curl.escape(battlegroup), page))
		local page = xml.parse(data):get_first_child("arenaLadderPagedResult"):get_first_child("arenaTeams")

		for team in page:iterate_children("arenaTeam") do
			get_arena_team(team)
		end
	end
end

local type = arg[1] or "bg"

if type == "bg" then
	get_battlegroup_info(arg[2] or BATTLEGROUP, arg[3] and tonumber(arg[3]) or MAX_PAGE)
elseif type == "guild" then
	get_guild_roster(arg[2], arg[3])
elseif type == "char" then
	get_character_info(arg[2], arg[3])
else
	print[=[
Usage: mine_player.lua [<type> [<...>]]
Where type is:
bg <battlegroup> <max_page>
guild <realm> <name>
character <realm> <name>
]=]
end
